package direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class EmitLogDirect {

    private static final String EXCHANGE_NAME = "direct_logs";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.208.134");
        factory.setUsername("admin");
        factory.setPassword("123");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

            // serverity: [info] [warning] [error]
            //String severity = getSeverity(argv);
            //String message = getMessage(argv);
            //channel.basicPublish(EXCHANGE_NAME, severity, null, message.getBytes(StandardCharsets.UTF_8));
            //System.out.println(" [x] Sent '" + severity + "':'" + message + "'");

            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String logData = scanner.nextLine();
                String logRoutingKey = getLogRoutingKey(logData);
                String logMessage = getLogMessage(logData);
                channel.basicPublish(EXCHANGE_NAME, logRoutingKey, null, logMessage.getBytes(StandardCharsets.UTF_8));
                System.out.println(" [x] Sent '" + logRoutingKey + "':'" + logMessage + "'");
            }
        }
    }

    private static String getLogMessage(String logData) {
        return logData.substring(logData.indexOf(" ") + 1);
    }

    private static String getLogRoutingKey(String logData) {
        return logData.substring(0, logData.indexOf(" "));
    }

    //private static String getSeverity(String[] strings) {
    //    if (strings.length < 1)
    //        return "info";
    //    return strings[0];
    //}
    //
    //private static String getMessage(String[] strings) {
    //    if (strings.length < 2)
    //        return "Hello World!";
    //    return joinStrings(strings, " ", 1);
    //}
    //
    //private static String joinStrings(String[] strings, String delimiter, int startIndex) {
    //    int length = strings.length;
    //    if (length == 0) return "";
    //    if (length <= startIndex) return "";
    //    StringBuilder words = new StringBuilder(strings[startIndex]);
    //    for (int i = startIndex + 1; i < length; i++) {
    //        words.append(delimiter).append(strings[i]);
    //    }
    //    return words.toString();
    //}
}
